package com.hsg.common.thirdloginutil.login.google

//import com.hsg.common.thirdloginutil.R
import android.app.Activity
import android.content.Intent
import android.content.IntentSender
import android.util.Log
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.IntentSenderRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.app.ActivityCompat.startIntentSenderForResult
import androidx.fragment.app.Fragment
import com.google.android.gms.auth.api.identity.BeginSignInRequest
import com.google.android.gms.auth.api.identity.Identity
import com.google.android.gms.auth.api.identity.SignInClient
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.common.api.ApiException
import com.google.android.gms.tasks.Task
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.GoogleAuthProvider
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
import com.hsg.common.thirdloginutil.bean.ThirdLoginRespond
import com.hsg.common.thirdloginutil.login.LoginInterface

/**
 * Google登入类
 */
class GoogleLogin(
//    private val activity: Activity,
    private val fragment: Fragment,
    /**
     * Google 服务器用户ID，在google-services.json中
     */
    private val googleServerClientId: String,
    /**
     * 是否只能使用已经登入过的Google账号
     */
    private val filterByAuthorizedAccounts: Boolean = false,
    private val loginCallback: (respond: ThirdLoginRespond?) -> Unit
) : LoginInterface {
    private var signInRequest: BeginSignInRequest? = null //one tap 登入使用
    private var oneTapClient: SignInClient? = null //one tap 登入使用
    private var auth: FirebaseAuth? = null //one tap 登入使用
    private val TAG = "GoogleLogin"

//    private val LOGIN_REQUEST_CODE_GOOGLE = 1102
    private var registerForActivityResult: ActivityResultLauncher<Intent>? = null
//
    init {
        registerForActivityResult = fragment.registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { activityResult ->
            handleLoginResult(0, 0, activityResult.data)
        }
    }

        override fun startLogin() {
            auth = Firebase.auth
            val user = auth?.currentUser
            Log.i(TAG, "current user : $user")
//        if (user != null) {
//            val respond = ThirdLoginRespond(user?.uid, "user?.", user?.displayName, userEmail = user?.email)
//            loginCallback(respond)
//            return
//        }

            val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestProfile()
                .requestEmail()
                .requestIdToken(googleServerClientId)
                .build()
            // Build a GoogleSignInClient with the options specified by gso.
            val mGoogleSignInClient: GoogleSignInClient = GoogleSignIn.getClient(fragment.requireActivity(), gso)
            val signInIntent = mGoogleSignInClient.signInIntent
            registerForActivityResult?.launch(signInIntent)

            /*oneTapClient = Identity.getSignInClient(fragment.requireActivity())
            signInRequest = BeginSignInRequest.builder()
                .setGoogleIdTokenRequestOptions(
                    BeginSignInRequest.GoogleIdTokenRequestOptions.builder()
                        .setSupported(true)
                        // Your server's client ID, not your Android client ID.
                        .setServerClientId(googleServerClientId)
                        // Only show accounts previously used to sign in.
                        .setFilterByAuthorizedAccounts(filterByAuthorizedAccounts)
                        .build()
                )
                .build()
            oneTapClient?.beginSignIn(signInRequest!!)
                ?.addOnSuccessListener(fragment.requireActivity()) { result ->
                    try {
//                        startIntentSenderForResult(
//                            activity,
//                            result.pendingIntent.intentSender, LOGIN_REQUEST_CODE_GOOGLE,
//                            null, 0, 0, 0, null
//                        )
                        registerForActivityResult?.launch(IntentSenderRequest.Builder(result.pendingIntent.intentSender).build())
                    } catch (e: IntentSender.SendIntentException) {
                        Log.e(TAG, "Couldn't start One Tap UI: ${e.localizedMessage}")
                        loginCallback(null)
                    }
                }
                ?.addOnFailureListener(fragment.requireActivity()) { e ->
                    // No saved credentials found. Launch the One Tap sign-up flow, or
                    // do nothing and continue presenting the signed-out UI.
                    Log.d(TAG, "Google beginSignIn OnFailureListener : ${e.localizedMessage}")
                    loginCallback(null)
                }
*/
        }

        override fun handleLoginResult(requestCode: Int, resultCode: Int, data: Intent?) {
//            when (requestCode) {
//                LOGIN_REQUEST_CODE_GOOGLE -> {
                   /* try {
                        val credential = oneTapClient?.getSignInCredentialFromIntent(data)
                        val idToken = credential?.googleIdToken
                        when {
                            idToken != null -> {
                                // Got an ID token from Google. Use it to authenticate
                                // with your backend.
                                Log.d(TAG, "Got ID token: $idToken")
//                            val respond = ThirdLoginRespond(credential.id, idToken, credential.displayName)
//                            loginCallback(respond)

                                val firebaseCredential = GoogleAuthProvider.getCredential(idToken, null)
                                auth?.signInWithCredential(firebaseCredential)
                                    ?.addOnCompleteListener(fragment.requireActivity()) { task ->
                                        if (task.isSuccessful) {
                                            // Sign in success, update UI with the signed-in user's information
                                            Log.d(TAG, "signInWithCredential:success")
                                            val user = auth?.currentUser
                                            val respond = ThirdLoginRespond(user?.uid, idToken, user?.displayName, userEmail = user?.email)
                                            loginCallback(respond)
                                        } else {
                                            // If sign in fails, display a message to the user.
                                            Log.w(TAG, "signInWithCredential:failure", task.exception)
                                            loginCallback(null)
                                        }
                                    }
                            }
                            else -> {
                                // Shouldn't happen.
                                Log.d(TAG, "No ID token or password!")
                                loginCallback(null)
                            }
                        }
                    } catch (e: ApiException) {
                        loginCallback(null)
                    }*/

                     try {
                         val task = GoogleSignIn.getSignedInAccountFromIntent(data)
                         val account = task.getResult(ApiException::class.java) as GoogleSignInAccount?
                         if (account != null) {
                             val respond = ThirdLoginRespond(account.id, account.idToken, account.displayName, userEmail = account.email)
                             loginCallback(respond)
                         } else {
                             loginCallback(null)
                         }
                     } catch (e: ApiException) {
                         e.printStackTrace()
                         loginCallback(null)
                     }

//                }
//            }
        }

        override fun signOut() {
//        mGoogleSignInClient?.signOut()
            if (auth == null) {
                Firebase.auth.signOut()
            } else {
                auth!!.signOut()
            }
        }

}